import chalk from 'chalk';
import { execa } from 'execa';
import readline from 'readline-sync'

const step = msg => console.log(chalk.cyan(msg));

const run = function (bin, args = [], opts = {}) {
  return execa(bin, args, { stdio: 'inherit', ...opts });
}

async function push2Remote() {
  try {
    step('校验master分支')
    await run('git', ['checkout', 'master']);
    await run('git', ['fetch', '--all']);
    await run('git', ['add', '--all']);
    let feat = readline.question('请输入新增功能：') ?? '',
      fix = readline.question('请输入修复功能：') ?? '';
    // 提交格式
    let commitFormatStr = ''
    if (fix.length > 0) {
      commitFormatStr = `feat: ${feat}\n fix: ${fix}\n`;
    }
    if(feat.length > 0) {
      commitFormatStr = `feat: ${feat}\n fix: ${fix}`;
    }
    await run('git', ['commit', '-m', commitFormatStr]);
    await run('git', ['rebase', 'origin/master']);
    await run('git', ['push', 'origin', 'master']);
    console.log(chalk.green('提交成功'));
  } catch (err) {
    console.log(err);
    console.log(chalk.red('提交失败'));
  }
}

async function main() {
  await push2Remote();
}
main();